package com.shengruan.admin.action;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.AdminJdbc;
import com.shengruan.admin.vo.Admin;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.Function;
import com.shengruan.common.Md5;
import com.shengruan.servlet.ServletUtils;


public class AdminLoginAction extends BaseAction {

     Logger logger = LoggerFactory.getLogger(AdminLoginAction.class);     

    private AdminJdbc adminJdbc = (AdminJdbc)this.getJdbc(AdminJdbc.class);

    @Override
    public void execute() throws Exception
    {

        String userName = this.input("userName");
        String password = this.input("password");
        String code = this.input("code");

        HttpSession session = request.getSession();

        //校验验证码
        String validateCode = (String) session.getAttribute("validateCode");
        if(StringUtils.isEmpty(validateCode) || code==null || !code.equalsIgnoreCase(validateCode)){
            ServletUtils.renderText(response, "errorCode");
            return;
        }
        Admin admin = adminJdbc.getByAdminName(userName);

        try {
            if (admin == null) {
            	this.print("errorPassword");
                return;
            } else {
                if (admin.getPassword().equalsIgnoreCase(new Md5().getMD5ofStr(password))) {

                    //该帐号被禁用
                    if(admin.getStatus() == Constants.STATUS_INACTIVE) {
                       this.print("errorStatus");
                        return;
                    }

                    admin.setLastloginTime(System.currentTimeMillis() + "");
                    admin.setLastloginIp(Function.getIpAddr(request));
                    admin.setLogins(admin.getLogins() + 1);
                    adminJdbc.updateAdmin(admin);

                    this.setSession(Constants.ADMIN, admin);
                    this.print("success");
                    return;
                } else {
                	this.print("errorPassword");
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.print("error");
            return ;
        }
    }
}
